/*
 * Copyright 2010 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.websocket;

import java.nio.charset.Charset;

/**
 * Sample extension that supports passing a MIME type.
 */
public class MimeTypeExtension implements Extension {

  /**
   * The data associated with the MIME type extension.
   */
  public class MimeTypeData implements ExtensionData {

    private final String mimeType;

    public MimeTypeData(String mimeType) {
      this.mimeType = mimeType;
    }

    public Extension getExtension() {
      return MimeTypeExtension.this;
    }

    /**
     * @return MIME type.
     */
    public String getMimeType() {
      return mimeType;
    }
  }

  private static final Charset UTF8 = Charset.forName("UTF-8");

  public byte[] generateExtensionData(ExtensionData data) {
    assert data instanceof MimeTypeData;
    MimeTypeData mtd = (MimeTypeData) data;
    return mtd.getMimeType().getBytes(UTF8);
  }

  public int getId() {
    return 14;
  }

  public String getName() {
    return "mime-type";
  }

  public ExtensionData parseExtensionData(byte[] bytes) {
    String mimeType = new String(bytes, UTF8);
    return new MimeTypeData(mimeType);
  }

  public boolean usesMetadata() {
    return true;
  }
}
